import type { Plugin } from 'vite'
import { existsSync, rmSync } from 'node:fs'
import { resolve } from 'node:path'

/**
 * Vite 插件：在构建前清空 release 目录
 */
export function cleanReleasePlugin(): Plugin {
  return {
    name: 'clean-release',
    buildStart() {
      const releaseDir = resolve(process.cwd(), 'release')

      if (existsSync(releaseDir)) {
        console.log('🧹 正在清理发布目录....')
        try {
          rmSync(releaseDir, { recursive: true, force: true })
          console.log('✅ 发布目录清理成功')
        } catch (error) {
          console.warn('⚠️ 清理发布目录失败:', error)
        }
      }
    }
  }
}
